package com.darcytech.debezium.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.client.methods.HttpPost;

import com.darcytech.debezium.common.network.HttpClientWrap;
import com.darcytech.debezium.common.utils.MD5Utils;
import com.darcytech.debezium.common.utils.ObjectMapperUtils;
import com.darcytech.debezium.trans.RegisterInfo;
import com.darcytech.debezium.trans.RegisterResult;

public class DefaultClient extends HttpClientWrap {

    private static final String secret = "000000";

    private static final long MAX_FAILURE_RETRY_TIME = 600000;

    private static final long DEFAULT_FAILURE_RETRY_TIME = 60000;

    private static final String BASE_PATH = "connectors/";

    private DefaultClient(final int poolMaxTotal, final int poolMaxPerRoute, final int connectTimeout, final int connectionRequestTimeout,
                          final int socketTimeout, final List<String> addresses, final long failureRetryTime) {
        super(poolMaxTotal, poolMaxPerRoute, connectTimeout, connectionRequestTimeout, socketTimeout, addresses, failureRetryTime);
    }

    private DefaultClient(final List<String> addresses, long failureRetryTime) {
        this(3, 3, 5000, 5000, 5000, addresses,
                Math.min(failureRetryTime, MAX_FAILURE_RETRY_TIME));

    }

    private DefaultClient(final List<String> addresses) {
        this(addresses, DEFAULT_FAILURE_RETRY_TIME);
    }

    public DefaultClient(final String address) {
        this(new ArrayList<>(Collections.singleton(address)));
    }

    public RegisterResult registerGroup(RegisterInfo registerInfo) throws IOException {
        String sign = MD5Utils.md5(ObjectMapperUtils.writeAsString(registerInfo) + secret);
        String result = execute(BASE_PATH + "/registerGroup?sign=" + sign, HttpPost.METHOD_NAME, registerInfo, null);
        return ObjectMapperUtils.readValue(result, RegisterResult.class);
    }

    public static void main(String[] args) throws IOException {
        Set<RegisterInfo.NodeInfo> nodeInfos = new HashSet<>();

        RegisterInfo.NodeInfo nodeInfo = new RegisterInfo.NodeInfo("172.17.56.146", "thanatos01", 3307);
        nodeInfo.setPassword("root");
        nodeInfo.setUser("root");
        nodeInfos.add(nodeInfo);

        Set<String> tables = new HashSet<>();

        tables.add("unicorn_inspection_result");
        tables.add("intent_result");

        RegisterInfo registerInfo = new RegisterInfo("test", nodeInfos, tables);

        DefaultClient defaultClient = new DefaultClient("127.0.0.1:8080");

        RegisterResult registerResult = defaultClient.registerGroup(registerInfo);
        System.out.println(registerResult.getCode());
        System.out.println(registerResult.getMessage());
    }

}
